<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-deptName>
              <el-input
                class="not-mongolia"
                type="input"
                placeholder="请选择部门"
                :disabled="true"
                v-model="formInfo.data.deptName"
              >
                <template #append>
                  <el-icon @click="_selectDept"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品</el-button
              >
            </template>
            <template v-slot:filter-deleteProduct>
              <el-button :disabled="!canDeleteProduct" @click="delProduct"
                >删除产品</el-button
              >
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber }}</p>
                  <p>{{ scope.row.brandName }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName }}</p>
                  <p>{{ scope.row.productCode }}</p>
                  <p>{{ scope.row.alias }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue }}</p>
                  <p>{{ scope.row.codeTypeValue }}</p>
                  <p>{{ scope.row.classifyValue }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard }}</p>
                  <p>{{ scope.row.unitName }}</p>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="99999999"
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>

    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :query="selectDeptInfo.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectDeptCallback"
    />
    <!-- 选择产品 -->
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:showDialog="productInfo.visible"
      :query="productInfo.query.queryMap"
      :query-params="productInfo.query.queryParams"
      :tableKey="productInfo.tableKey"
      :showPrice="$permission('useTemplate:price')"
      :checkBoxSlotObj="checkBoxSlotObj"
      @callback="selectProduct"
    />
  </div>
</template>

<script setup name="useTemplateModify">
import {
  getUseTemplateDetailCustomizeList,
  createUseTemplate,
  updateUseTemplate,
  getUseTemplate,
  detailUseApplication,
  getUseApplicationDetailCustomizeList,
} from '../../../api/use'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps([
  'visible',
  'id',
  'title',
  'useApplicationOrderId',
  'isCopy',
])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref([])
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },

  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'deleteProduct',
    },
  ],
})
const checkBoxSlotObj = ref({
  // 搜索按钮后显示复选框
  showCheckBox: true,
  // 复选框文件描述
  checkLabel: '是否部门产品',
  checkBoxBool: true,
  // 复选框点击选中传值
  checkParams: {
    deptId: '',
    checkDeptProduct: 1,
  },
  // 复选框未选中传值
  noCheckParams: {
    deptId: '',
    checkDeptProduct: '',
  },
})
const filterInfoUseApplication = reactive({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      deptId: null,
    },
  },
})
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    name: '',
  },
  fieldList: [
    {
      label: '模板名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [
      {
        required: true,
        message: '请输入名称',
        trigger: 'blur',
      },
    ],
    deptName: [
      {
        required: true,
        message: '请选择部门',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    { value: 'price', show: 'false' },
    {
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: delProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectDeptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
//选择产品相关
let productInfo = reactive({
  visible: false,
  tableKey:
    'useApplicationTemplateModifyProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      checkDeptProduct: 1,
      deptId: null,
    },
  },
})
watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
      row.productionDate =
        row.productionDate === '1900-01-01' ? undefined : row.productionDate
    })
  },
  {
    deep: true,
  }
)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.length > 0
})
const canDeleteProduct = computed(() => {
  return tableInfo.selections.length
})
const canAddProduct = computed(() => {
  return formInfo.data.deptId
})

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    showUnitName: true, //是否显示单位
    showQty: true, //大小单位数量输入单元格是否显示计算后的qty
    isCalculation: false, //是否计算得到大小单位最大输入值
    largeUnitQty: 'largeUnitQty',
    smallUnitQty: 'smallUnitQty',
    largeRules: [
      { validator: proxy.$validate.positive, trigger: 'blur' },
      { validator: proxy.$validate.positive, trigger: 'change' },
    ],
    smallRules: [
      { validator: proxy.$validate.positive, trigger: 'blur' },
      { validator: proxy.$validate.positive, trigger: 'change' },
    ],
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useTemplate:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useTemplate:price'),
    hidden: true,
  },

  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useTemplate:price'),
    hidden: true,
  },
  defaultSupplierName: {
    label: '默认供应商',
    value: 'defaultSupplierName',
    type: 'column',
    hidden: true,
  },
  defaultSupplierCode: {
    label: '默认供应商编码',
    value: 'defaultSupplierCode',
    type: 'column',
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
if (!props.id) {
  formInfo.fieldList = formInfo.fieldList.filter(
    (item) => item.value !== 'orderNo'
  )
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
// 获取列表
function getList() {
  getUseTemplateDetailCustomizeList(filterInfo.query).then((res) => {
    if (res && res.success) {
      const prodeuctsData = generateProductKey(res.data)
      tableInfo.data = prodeuctsData
    }
  })
}
function getMain() {
  getUseTemplate(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      productInfo.query.queryParams.deptId = formInfo.data.deptId
    }
  })
  getList()
}
function getUseApplicationOrderDetail() {
  detailUseApplication(props.useApplicationOrderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.data.deptId = resp.data.deptId
      formInfo.data.deptName = resp.data.deptName
      let param = {
        tableKey:
          'useApplicationOrderDetail-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
      }
      getCustomizeSetting(param).then((res) => {
        if (res && res.success) {
          let data = res.data
          filterInfoUseApplication.query.customizeUserVO = data
          filterInfoUseApplication.query.queryMap.orderId.value =
            props.useApplicationOrderId
          getUseApplicationDetailCustomizeList(
            filterInfoUseApplication.query
          ).then((resp) => {
            if (resp && resp.success) {
              const data = resp.data.map(function (item) {
                return {
                  ...item,
                  defaultSupplierPrice: item.price,
                  defaultSupplierId: item.supplierId,
                  defaultSupplierName: item.supplierName,
                  defaultSupplierCode: item.supplierCode,
                }
              })
              tableInfo.data = data.concat(tableInfo.data)
            }
          })
        }
      })
    }
  })
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const data = formInfo.data
    if (!tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    data.details = proxy.$fn.filterBlacklist(tableInfo.data)
    if (props.isCopy) {
      delete data.id
    }
    const api = data.id && !props.isCopy ? updateUseTemplate : createUseTemplate
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
//添加产品
function addProduct() {
  const productIds = tableInfo.data.map((item) => item.productId)
  productInfo.query.queryMap.id.value = productIds.toString()
  productInfo.query.queryParams.deptId = formInfo.data.deptId
  checkBoxSlotObj.value.checkParams = {
    deptId: formInfo.data.deptId,
  }
  productInfo.visible = true
}
//删除产品
function delProduct(data = undefined) {
  if (tableInfo.selections.length > 0) {
    tableInfo.data = tableInfo.data.filter(
      (row) => !tableInfo.selections.includes(row)
    )
  } else if (data && data.id) {
    tableInfo.data = tableInfo.data.filter((row) => data !== row)
  }
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
        productId: item.id,
        largeUnitQty: item.largeUnitQty || 0,
        smallUnitQty: item.smallUnitQty || 0,
        qty: item.qty || 0,
        calcQty: item.calcQty || 0,
        defaultSupplierPrice: item.price,
        defaultSupplierId: item.supplierId,
        defaultSupplierName: item.supplierName,
        defaultSupplierCode: item.supplierCode,
      }
    })
    tableInfo.data = data.concat(tableInfo.data)
  }
}
//选择部门
function _selectDept() {
  selectDeptInfo.visible = true
}
function selectDeptCallback(row) {
  if (row) {
    if (row.id !== formInfo.data.deptId) {
      formInfo.data['deptName'] = row.name
      formInfo.data['deptId'] = row.id
    }
  } else {
    formInfo.data['deptName'] = ''
    formInfo.data['deptId'] = ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationTemplateModify-com.slip.spd.entity.vo.use.UseTemplateDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      if (props.id) {
        getMain()
      }
      if (props.useApplicationOrderId) {
        getUseApplicationOrderDetail()
      }
    }
  })
}
</script>
